import Sker from '@/utils/sker'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.less'
import cm from 'classnames'
import Button from '../button'
import SearchSvg from '@/svg/search'
import { getUsersLikes } from '@/api/admin'
import { useSetState } from 'ahooks'
import { debounce } from 'lodash-es'
import { isElementInViewport } from '@/utils/utils'
import Loading from '@/components/fetch-loading'

function Select(props) {
  const { width = 248, placeholder = '人员筛选', onSubmit } = props
  const selectEventName = useRef(Symbol('select'))
  const inputRef = useRef(null)
  const scrollRef = useRef(null)
  const [dataInfo, setDataInfo] = useSetState({
    pageSize: 10,
    list: [],
    selectVal: [],
    expend: false,
    init:false,
    isEnd:false,
    isLoading:false
  })
  const [pageNo, setPageNo] = useState(1)

  // 当前选中值
  const placeholders = useMemo(() => {
    if (!dataInfo.selectVal.length) {
      return placeholder
    } else if (dataInfo.selectVal.length === 1) {
      return dataInfo.selectVal[0].email
    } else {
      return (
        <>
          <div className={cm(styles.txt, 'textEllipsis')}>{dataInfo.selectVal[0].email}</div>
          <div className={styles.count}>+{dataInfo.selectVal.length - 1}</div>
        </>
      )
    }
  }, [dataInfo.selectVal])

  const select = (e, curr) => {
    e.stopPropagation()
    const isSelected = dataInfo.selectVal.find((item) => item.id === curr.id)
    let data = [...dataInfo.selectVal]
    if (isSelected) {
      data = data.filter((item) => item.id !== curr.id)
    } else {
      data.push(curr)
    }
    setDataInfo({ selectVal: data })
  }

  // 展开收起select
  const selectClick = (ev) => {
    ev.stopPropagation()
    Sker.dispatch('select', { name: selectEventName.current })
    setDataInfo({ expend: !dataInfo.expend })
  }

  const clearData = (e) => {
    e.stopPropagation()
    setDataInfo({ selectVal: [] })
    onSubmit([])
  }

  const filterData = async () => {
    const searchEmail = inputRef.current.value
    const res = await getUsersLikes({
      page: 1,
      pageSize: dataInfo.pageSize,
      searchEmail,
    })
    if (!res.code) {
      setDataInfo({ list: res.data.list || [] })
    }
  }
  const debounceFilter = debounce(filterData, 800)

  // 全局click点击，Select失焦
  useEffect(() => {
    setDataInfo({init:true})
    const click = () => {
      setDataInfo({ expend: false })
    }
    const removeListen = Sker.listen('select', (event) => {
      if (event.detail.name !== selectEventName.current) {
        setDataInfo({ expend: false })
      }
    })
    const scrollListen = debounce(handleScroll, 500)
    scrollRef.current.addEventListener('scroll', scrollListen)
    window.addEventListener('click', click)
    return () => {
      removeListen()
      window.removeEventListener('click', click)
      scrollRef?.current?.removeEventListener('scroll', scrollListen)
    }
  }, [])

  const handleScroll = () => {
    if (isElementInViewport(scrollRef.current)) {
      setPageNo(page => page + 1)
    }
  }

  // page变化，加载数据
  useEffect(() => {
    if(!dataInfo.init){
      getUsersLikes({ page: 1, pageSize: dataInfo.pageSize }).then((res) => {
        if (!res.code) {
          const data = res.data.list || []
          setDataInfo({ list:data,isEnd:data.length < dataInfo.pageSize })
        }
      })
      return
    }
    if (dataInfo.isEnd) return
    const searchEmail = inputRef.current.value
    setDataInfo({isLoading:true})
    getUsersLikes({ page: pageNo, pageSize: dataInfo.pageSize,searchEmail }).then((res) => {
      if (!res.code) {
        const data = res.data.list || []
        setDataInfo({ isLoading:false,list:[...dataInfo.list,...data],isEnd:data.length < dataInfo.pageSize })
      }
    })
  }, [pageNo])
  //提交
  const submit = () => {
    const ids = dataInfo.selectVal.map((item) => item.id)
    onSubmit(ids)
    setDataInfo({ expend: false })
  }

  return (
    <div style={{ width, ...props.style }} className={styles['select-container']}>
      <div className={styles['select-title']} onClick={selectClick}>
        <div className={cm(styles['select-title-text'], 'textEllipsis')}>{placeholders}</div>
        <div className={styles.imgBox}>
          <img
            src="/images/arrow.png"
            alt=""
            className={cm(styles['select-title-arrow'], dataInfo.expend ? styles.activeEnter : styles.activeLeave)}
          />
          <img src="/images/close.webp" alt="" className={styles['select-title-clear']} onClick={clearData} />
        </div>
      </div>
       <div
          className={cm(styles['select-options-items'], {
            [styles['select-options-items-flex']]: !dataInfo.list.length,
            'hidden':!dataInfo.expend
          })}
          style={{display:!dataInfo.expend ? 'none':'flex'}}
          onClick={(e) => e.stopPropagation()}
        >
          <div className={styles['options-top']}>
            <div className={styles.filter}>
              <input maxLength={100} type="text" placeholder="请输入名称" ref={inputRef} onInput={debounceFilter} />
              <SearchSvg className={styles.search} fill="#aaa" />
            </div>
            {!dataInfo.list.length ? (
              <div className={styles.nullBox}>
                <img src="/images/null-select.png" alt="" />
                <div>暂无数据</div>
              </div>
            ) : null}
            <ul className={styles.selectBox} ref={scrollRef}>
              {dataInfo.list.map((item, index) => (
                <li
                  title={item.email}
                  key={index}
                  onClick={(e) => select(e, item)}
                  className={cm(styles['select-item'], {
                    [styles.active]: dataInfo.selectVal.filter((curr) => curr.id === item.id).length,
                  })}
                >
                  <span className={styles.checked}></span>
                  <div className={cm(styles.user, 'textEllipsis')}> {item.email}</div>
                </li>
              ))}
              {dataInfo.isLoading && <Loading width={10} />}
            </ul>
          </div>
          <div className={styles['options-bottom']}>
            <Button className={styles.btn} onClick={() => setDataInfo({ expend: false })}>
              取消
            </Button>
            <Button className={cm(styles.btn, styles.btnSure)} type="theme" onClick={submit}>
              确定
            </Button>
          </div>
        </div>
    </div>
  )
}

const Index = React.memo(Select)

export default Index
